<template>
  <div class="app-stats">
    <NavBar />
    
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="el-icon-arrow-left">返回</el-button>
        <h1>{{ appName }} - 数据统计</h1>
      </div>
      <div class="header-right">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
        />
        <el-button type="primary" @click="exportData" icon="el-icon-download">导出数据</el-button>
      </div>
    </div>

    <!-- 核心指标卡片 -->
    <div class="stats-cards">
      <div class="stat-card" v-for="(stat, index) in coreMetrics" :key="index">
        <div class="stat-header">
          <h3>{{ stat.title }}</h3>
          <el-tooltip :content="stat.tip" placement="top">
            <i class="el-icon-info"></i>
          </el-tooltip>
        </div>
        <div class="stat-value">{{ stat.value }}</div>
        <div class="stat-change" :class="stat.change > 0 ? 'positive' : 'negative'">
          <i :class="stat.change > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
          {{ Math.abs(stat.change) }}%
        </div>
        <div class="stat-trend">
          <div class="mini-chart" :id="`chart-${index}`"></div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <div class="chart-container">
        <div class="chart-header">
          <h3>安装趋势</h3>
          <div class="chart-actions">
            <el-radio-group v-model="trendType" size="small" @change="updateTrendChart">
              <el-radio-button label="install">安装量</el-radio-button>
              <el-radio-button label="conversion">转化率</el-radio-button>
              <el-radio-button label="retention">留存率</el-radio-button>
            </el-radio-group>
            <el-button-group size="small">
              <el-button icon="el-icon-refresh" @click="resetChartZoom">重置</el-button>
              <el-button icon="el-icon-download" @click="exportChart('trend')">导出</el-button>
            </el-button-group>
          </div>
        </div>
        <div class="chart-content" id="trend-chart"></div>
      </div>

      <div class="chart-container">
        <div class="chart-header">
          <h3>渠道分布</h3>
          <div class="chart-actions">
            <el-select v-model="channelType" size="small" @change="updateChannelChart">
              <el-option label="安装来源" value="source" />
              <el-option label="设备类型" value="device" />
              <el-option label="地域分布" value="region" />
            </el-select>
            <el-button-group size="small">
              <el-button icon="el-icon-download" @click="exportChart('channel')">导出</el-button>
            </el-button-group>
          </div>
        </div>
        <div class="chart-content" id="channel-chart"></div>
      </div>
    </div>

    <!-- 详细数据表格 -->
    <div class="data-table-section">
      <div class="table-header">
        <h3>详细数据</h3>
        <div class="table-actions">
          <el-input
            v-model="searchQuery"
            placeholder="搜索渠道、设备型号..."
            prefix-icon="el-icon-search"
            style="width: 250px"
            @input="handleTableSearch"
          />
          <el-select v-model="tablePageSize" size="small" @change="handlePageSizeChange">
            <el-option label="10条/页" :value="10" />
            <el-option label="20条/页" :value="20" />
            <el-option label="50条/页" :value="50" />
          </el-select>
        </div>
      </div>
      
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="channel" label="渠道" width="150" />
        <el-table-column prop="device" label="设备型号" width="150" />
        <el-table-column prop="installs" label="安装数" width="100" sortable />
        <el-table-column prop="clicks" label="点击数" width="100" sortable />
        <el-table-column prop="conversion" label="转化率" width="100" sortable>
          <template #default="scope">
            {{ scope.row.conversion }}%
          </template>
        </el-table-column>
        <el-table-column prop="retention" label="次日留存" width="100" sortable>
          <template #default="scope">
            {{ scope.row.retention }}%
          </template>
        </el-table-column>
        <el-table-column prop="fraud" label="作弊率" width="100" sortable>
          <template #default="scope">
            <span :style="{ color: scope.row.fraud > 5 ? '#f56c6c' : '#67c23a' }">
              {{ scope.row.fraud }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="viewDetail(scope.row)">详情</el-button>
            <el-button type="text" @click="exportRow(scope.row)">导出</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="tablePageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"
        />
      </div>
    </div>

    <!-- 实时数据监控 -->
    <div class="realtime-section">
      <div class="realtime-header">
        <h3>实时监控</h3>
        <div class="realtime-status">
          <span class="status-indicator" :class="{ active: isRealtimeActive }"></span>
          {{ isRealtimeActive ? '监控中' : '已暂停' }}
        </div>
      </div>
      <div class="realtime-grid">
        <div class="realtime-item" v-for="(item, index) in realtimeData" :key="index">
          <div class="realtime-label">{{ item.label }}</div>
          <div class="realtime-value">{{ item.value }}</div>
          <div class="realtime-change" :class="item.change > 0 ? 'positive' : 'negative'">
            {{ item.change > 0 ? '+' : '' }}{{ item.change }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import NavBar from '@/components/NavBarEnhanced.vue';
import { Chart, registerables } from 'chart.js';
import { appStatisticsApi, getSDKStatsApi } from '@/api/apps';

Chart.register(...registerables);

export default {
  components: {
    NavBar
  },
  data() {
    return {
      appId: '',
      appkey: '',
      appName: '',
      dateRange: [],
      trendType: 'install',
      channelType: 'source',
      searchQuery: '',
      tablePageSize: 20,
      currentPage: 1,
      totalItems: 0,
      tableLoading: false,
      isRealtimeActive: true,
      
      coreMetrics: [
        {
          title: '总安装数',
          value: '0',
          change: 0,
          tip: '统计周期内的总安装数量'
        },
        {
          title: '独立用户数',
          value: '0',
          change: 0,
          tip: '去重后的独立用户数量'
        },
        {
          title: '平均转化率',
          value: '0%',
          change: 0,
          tip: '点击到安装的转化率'
        },
        {
          title: '成功率',
          value: '0%',
          change: 0,
          tip: 'SDK请求成功率'
        }
      ],
      
      tableData: [],
      realtimeData: [],
      
      // 图表实例
      trendChart: null,
      channelChart: null,
      miniCharts: [],
      
      // 统计数据
      sdkStats: null,
      appStats: null,
      
      // 数据缓存
      dataCache: new Map(),
      cacheTimeout: 5 * 60 * 1000, // 5分钟缓存
      
      // 图表配置
      chartExportOptions: {
        width: 1200,
        height: 600,
        backgroundColor: '#ffffff'
      }
    };
  },
  
  mounted() {
    this.appId = this.$route.query.id;
    this.appName = this.$route.query.name || '应用';
    this.appkey = this.$route.query.appkey || '';
    this.initDateRange();
    this.loadData();
    this.startRealtimeMonitoring();
    this.initCharts();
  },
  
  beforeDestroy() {
    this.stopRealtimeMonitoring();
    this.destroyCharts();
  },
  
  methods: {
    initDateRange() {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 30);
      this.dateRange = [start, end];
    },
    
    async loadData() {
      this.tableLoading = true;
      try {
        // 加载应用统计数据
        const appStatsResponse = await appStatisticsApi(this.appId);
        if (appStatsResponse.code === 200) {
          this.appStats = appStatsResponse.data;
          this.updateCoreMetrics();
        }
        
        // 加载SDK统计数据
        if (this.appkey) {
          const sdkStatsResponse = await getSDKStatsApi(this.appkey, 30);
          if (sdkStatsResponse.code === 200) {
            this.sdkStats = sdkStatsResponse.data;
            this.updateCharts();
          }
        }
        
        this.loadTableData();
        this.loadRealtimeData();
      } catch (error) {
        console.error('加载数据失败:', error);
        this.$message.error('数据加载失败');
      } finally {
        this.tableLoading = false;
      }
    },
    
    updateCoreMetrics() {
      if (this.sdkStats && this.sdkStats.summary) {
        const summary = this.sdkStats.summary;
        
        this.coreMetrics = [
          {
            title: '总请求数',
            value: summary.total_requests.toLocaleString(),
            change: this.calculateChange(summary.total_requests, this.getPreviousPeriodRequests()),
            tip: '统计周期内的总SDK请求数'
          },
          {
            title: '独立用户数',
            value: this.estimateUniqueUsers(),
            change: 8.7,
            tip: '基于设备指纹估算的独立用户数量'
          },
          {
            title: '平均响应时间',
            value: summary.avg_response_time + 'ms',
            change: this.calculateResponseTimeChange(),
            tip: 'SDK请求平均响应时间'
          },
          {
            title: '成功率',
            value: summary.success_rate + '%',
            change: this.calculateSuccessRateChange(),
            tip: 'SDK请求成功率'
          }
        ];
      }
    },
    
    estimateUniqueUsers() {
      // 基于设备指纹估算独立用户数
      if (this.sdkStats && this.sdkStats.usage) {
        const uniqueFingerprints = new Set();
        this.sdkStats.usage.forEach(stat => {
          // 这里假设数据中包含fingerprint信息
          // 实际使用时需要根据真实数据结构进行调整
        });
        return Math.floor(this.sdkStats.summary.total_requests * 0.8).toLocaleString();
      }
      return '0';
    },
    
    calculateChange(current, previous) {
      if (previous === 0) return 0;
      return parseFloat(((current - previous) / previous * 100).toFixed(1));
    },
    
    getPreviousPeriodRequests() {
      // 这里应该获取上一周期的数据进行比较
      // 暂时返回一个估算值
      return Math.floor(this.sdkStats.summary.total_requests * 0.9);
    },
    
    calculateResponseTimeChange() {
      // 计算响应时间变化
      return -5.2; // 模拟数据
    },
    
    calculateSuccessRateChange() {
      // 计算成功率变化
      return 2.1; // 模拟数据
    },
    
    initCharts() {
      this.$nextTick(() => {
        this.initTrendChart();
        this.initChannelChart();
        this.initMiniCharts();
      });
    },
    
    initTrendChart() {
      const ctx = document.getElementById('trend-chart');
      if (!ctx) return;
      
      this.trendChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: this.generateDateLabels(7),
          datasets: [{
            label: 'SDK请求数',
            data: this.generateTrendData(7),
            borderColor: '#409EFF',
            backgroundColor: 'rgba(64, 158, 255, 0.1)',
            tension: 0.4,
            fill: true,
            pointBackgroundColor: '#409EFF',
            pointBorderColor: '#fff',
            pointBorderWidth: 2,
            pointRadius: 4,
            pointHoverRadius: 6
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          interaction: {
            intersect: false,
            mode: 'index'
          },
          plugins: {
            legend: {
              display: false
            },
            tooltip: {
              backgroundColor: 'rgba(0, 0, 0, 0.8)',
              titleColor: '#fff',
              bodyColor: '#fff',
              borderColor: '#409EFF',
              borderWidth: 1,
              cornerRadius: 4,
              displayColors: false,
              callbacks: {
                title: function(context) {
                  return `日期: ${context[0].label}`;
                },
                label: function(context) {
                  return `请求数: ${context.parsed.y.toLocaleString()}`;
                }
              }
            },
            zoom: {
              zoom: {
                wheel: {
                  enabled: true,
                },
                pinch: {
                  enabled: true
                },
                mode: 'x',
              },
              pan: {
                enabled: true,
                mode: 'x',
              }
            }
          },
          scales: {
            y: {
              beginAtZero: true,
              grid: {
                color: 'rgba(0,0,0,0.1)'
              },
              ticks: {
                callback: function(value) {
                  return value.toLocaleString();
                }
              }
            },
            x: {
              grid: {
                display: false
              }
            }
          },
          onClick: (event, elements) => {
            if (elements.length > 0) {
              const index = elements[0].index;
              const label = this.trendChart.data.labels[index];
              const value = this.trendChart.data.datasets[0].data[index];
              this.$message.info(`${label}: ${value.toLocaleString()} 次请求`);
            }
          }
        }
      });
    },
    
    initChannelChart() {
      const ctx = document.getElementById('channel-chart');
      if (!ctx) return;
      
      this.channelChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
          labels: ['设备信息', '自定义参数', '事件追踪'],
          datasets: [{
            data: this.generateChannelData(),
            backgroundColor: [
              '#409EFF',
              '#67C23A',
              '#E6A23C'
            ]
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: 'bottom'
            }
          }
        }
      });
    },
    
    initMiniCharts() {
      this.coreMetrics.forEach((metric, index) => {
        const ctx = document.getElementById(`chart-${index}`);
        if (!ctx) return;
        
        const miniChart = new Chart(ctx, {
          type: 'line',
          data: {
            labels: ['', '', '', '', ''],
            datasets: [{
              data: this.generateMiniChartData(),
              borderColor: metric.change > 0 ? '#67C23A' : '#F56C6C',
              backgroundColor: 'transparent',
              tension: 0.4,
              pointRadius: 0,
              borderWidth: 2
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                display: false
              }
            },
            scales: {
              x: {
                display: false
              },
              y: {
                display: false
              }
            }
          }
        });
        
        this.miniCharts.push(miniChart);
      });
    },
    
    generateDateLabels(days) {
      const labels = [];
      for (let i = days - 1; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        labels.push(date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }));
      }
      return labels;
    },
    
    generateTrendData(days) {
      const data = [];
      for (let i = 0; i < days; i++) {
        data.push(Math.floor(Math.random() * 1000) + 100);
      }
      return data;
    },
    
    generateChannelData() {
      if (this.sdkStats && this.sdkStats.usage) {
        const endpointData = {};
        this.sdkStats.usage.forEach(stat => {
          if (!endpointData[stat.endpoint]) {
            endpointData[stat.endpoint] = 0;
          }
          endpointData[stat.endpoint] += stat.count;
        });
        
        return Object.values(endpointData);
      }
      return [300, 200, 100]; // 默认数据
    },
    
    generateMiniChartData() {
      const data = [];
      for (let i = 0; i < 5; i++) {
        data.push(Math.floor(Math.random() * 100));
      }
      return data;
    },
    
    updateCharts() {
      if (this.trendChart) {
        this.trendChart.data.datasets[0].data = this.generateTrendData(7);
        this.trendChart.update();
      }
      
      if (this.channelChart) {
        this.channelChart.data.datasets[0].data = this.generateChannelData();
        this.channelChart.update();
      }
    },
    
    destroyCharts() {
      if (this.trendChart) {
        this.trendChart.destroy();
      }
      if (this.channelChart) {
        this.channelChart.destroy();
      }
      this.miniCharts.forEach(chart => {
        if (chart) {
          chart.destroy();
        }
      });
    },
    
    loadTableData() {
      this.tableLoading = true;
      // 模拟API调用
      setTimeout(() => {
        this.tableData = this.generateTableData();
        this.totalItems = this.tableData.length;
        this.tableLoading = false;
      }, 1000);
    },
    
    generateTableData() {
      const data = [];
      const endpoints = ['设备信息', '自定义参数', '事件追踪'];
      const statuses = ['success', 'error'];
      
      for (let i = 0; i < 50; i++) {
        const status = statuses[Math.floor(Math.random() * statuses.length)];
        data.push({
          date: new Date(Date.now() - i * 24 * 60 * 60 * 1000).toLocaleDateString('zh-CN'),
          endpoint: endpoints[Math.floor(Math.random() * endpoints.length)],
          status: status === 'success' ? '成功' : '失败',
          response_time: Math.floor(Math.random() * 200) + 50,
          count: Math.floor(Math.random() * 100) + 10,
          success_rate: (Math.random() * 20 + 80).toFixed(1)
        });
      }
      return data;
    },
    
    loadRealtimeData() {
      this.realtimeData = [
        { label: '当前在线', value: '1,234', change: 23 },
        { label: '今日点击', value: '5,678', change: 156 },
        { label: '今日安装', value: '890', change: -12 },
        { label: '实时转化率', value: '15.6%', change: 2.3 }
      ];
    },
    
    startRealtimeMonitoring() {
      this.realtimeTimer = setInterval(() => {
        if (this.isRealtimeActive) {
          this.updateRealtimeData();
        }
      }, 5000);
    },
    
    stopRealtimeMonitoring() {
      if (this.realtimeTimer) {
        clearInterval(this.realtimeTimer);
      }
    },
    
    updateRealtimeData() {
      this.realtimeData.forEach(item => {
        const change = (Math.random() - 0.5) * 20;
        item.change = parseFloat(change.toFixed(1));
      });
    },
    
    handleDateChange() {
      this.loadData();
    },
    
    handleTableSearch() {
      // 表格搜索逻辑
      this.loadTableData();
    },
    
    handlePageSizeChange() {
      this.currentPage = 1;
      this.loadTableData();
    },
    
    handleSizeChange(val) {
      this.tablePageSize = val;
      this.loadTableData();
    },
    
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadTableData();
    },
    
    updateTrendChart() {
      // 更新趋势图表
      this.updateCharts();
      this.$message.info(`切换到${this.trendType}数据`);
    },
    
    updateChannelChart() {
      // 更新渠道图表
      this.updateCharts();
      this.$message.info(`切换到${this.channelType}数据`);
    },
    
    viewDetail(row) {
      this.$message.info(`查看 ${row.date} 的详细数据`);
    },
    
    exportRow(row) {
      this.$message.success(`正在导出 ${row.date} 的数据...`);
    },
    
    async exportData() {
      try {
        this.$message.info('正在准备导出数据...');
        
        // 准备导出数据
        const exportData = {
          appInfo: {
            name: this.appName,
            appkey: this.appkey,
            exportTime: new Date().toLocaleString('zh-CN'),
            dateRange: this.dateRange.map(d => d.toLocaleDateString('zh-CN'))
          },
          coreMetrics: this.coreMetrics,
          sdkStats: this.sdkStats,
          tableData: this.tableData,
          charts: {
            trendChart: this.trendChart ? this.trendChart.data : null,
            channelChart: this.channelChart ? this.channelChart.data : null
          }
        };
        
        // 生成JSON文件
        const dataStr = JSON.stringify(exportData, null, 2);
        const dataBlob = new Blob([dataStr], { type: 'application/json' });
        const url = URL.createObjectURL(dataBlob);
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = url;
        link.download = `xapptool-stats-${this.appName}-${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // 释放URL对象
        URL.revokeObjectURL(url);
        
        this.$message.success('数据导出成功！');
      } catch (error) {
        console.error('导出数据失败:', error);
        this.$message.error('数据导出失败，请重试');
      }
    },
    
    goBack() {
      this.$router.push('/console');
    },
    
    // 数据缓存相关方法
    getCacheKey(type, params = {}) {
      return `${type}-${JSON.stringify(params)}-${this.appkey}`;
    },
    
    setCache(key, data) {
      this.dataCache.set(key, {
        data: data,
        timestamp: Date.now()
      });
    },
    
    getCache(key) {
      const cached = this.dataCache.get(key);
      if (cached && (Date.now() - cached.timestamp) < this.cacheTimeout) {
        return cached.data;
      }
      return null;
    },
    
    clearExpiredCache() {
      const now = Date.now();
      for (const [key, value] of this.dataCache.entries()) {
        if (now - value.timestamp > this.cacheTimeout) {
          this.dataCache.delete(key);
        }
      }
    },
    
    // 图表导出功能
    async exportChart(chartType) {
      try {
        let chart;
        let filename;
        
        switch (chartType) {
          case 'trend':
            chart = this.trendChart;
            filename = `趋势图-${this.appName}-${new Date().toISOString().split('T')[0]}.png`;
            break;
          case 'channel':
            chart = this.channelChart;
            filename = `渠道分布-${this.appName}-${new Date().toISOString().split('T')[0]}.png`;
            break;
          default:
            this.$message.warning('不支持的图表类型');
            return;
        }
        
        if (!chart) {
          this.$message.warning('图表尚未加载完成');
          return;
        }
        
        // 获取图表的canvas元素
        const canvas = chart.canvas;
        
        // 创建新的canvas用于导出（添加背景色）
        const exportCanvas = document.createElement('canvas');
        const exportCtx = exportCanvas.getContext('2d');
        
        exportCanvas.width = this.chartExportOptions.width;
        exportCanvas.height = this.chartExportOptions.height;
        
        // 填充背景色
        exportCtx.fillStyle = this.chartExportOptions.backgroundColor;
        exportCtx.fillRect(0, 0, exportCanvas.width, exportCanvas.height);
        
        // 绘制图表
        exportCtx.drawImage(canvas, 0, 0, exportCanvas.width, exportCanvas.height);
        
        // 转换为blob并下载
        exportCanvas.toBlob((blob) => {
          if (blob) {
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            
            this.$message.success('图表导出成功！');
          } else {
            this.$message.error('图表导出失败');
          }
        }, 'image/png');
        
      } catch (error) {
        console.error('导出图表失败:', error);
        this.$message.error('图表导出失败，请重试');
      }
    },
    
    // 重置图表缩放
    resetChartZoom() {
      if (this.trendChart) {
        this.trendChart.resetZoom();
        this.$message.info('图表缩放已重置');
      }
    }
  }
};
</script>

<style scoped>
.app-stats {
  padding: 0;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  background: white;
  padding: 1.5rem 2rem;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.header-left h1 {
  margin: 0;
  color: #303133;
  font-size: 1.5rem;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 1rem;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
  padding: 2rem;
}

.stat-card {
  background: white;
  padding: 1.5rem;
  border-radius: 0.5rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.stat-header h3 {
  margin: 0;
  color: #909399;
  font-size: 0.9rem;
  font-weight: normal;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  color: #303133;
  margin-bottom: 0.5rem;
}

.stat-change {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  font-size: 0.9rem;
  margin-bottom: 1rem;
}

.stat-change.positive {
  color: #67c23a;
}

.stat-change.negative {
  color: #f56c6c;
}

.mini-chart {
  height: 50px;
  width: 100%;
}

/* 图表区域 */
.charts-section {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 1.5rem;
  padding: 0 2rem 2rem;
}

.chart-container {
  background: white;
  border-radius: 0.5rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chart-header {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3 {
  margin: 0;
  color: #303133;
  font-size: 1.1rem;
}

.chart-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.chart-content {
  height: 300px;
  padding: 1rem;
}

/* 数据表格 */
.data-table-section {
  padding: 0 2rem 2rem;
}

.table-header {
  background: white;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 0.5rem 0.5rem 0 0;
}

.table-header h3 {
  margin: 0;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.pagination {
  background: white;
  padding: 1rem;
  border-radius: 0 0 0.5rem 0.5rem;
  display: flex;
  justify-content: center;
}

/* 实时监控 */
.realtime-section {
  padding: 0 2rem 2rem;
}

.realtime-header {
  background: white;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 0.5rem 0.5rem 0 0;
}

.realtime-header h3 {
  margin: 0;
  color: #303133;
}

.realtime-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #909399;
  font-size: 0.9rem;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #c0c4cc;
}

.status-indicator.active {
  background: #67c23a;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(103, 194, 58, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
  }
}

.realtime-grid {
  background: white;
  padding: 1.5rem;
  border-radius: 0 0 0.5rem 0.5rem;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem;
}

.realtime-item {
  text-align: center;
  padding: 1rem;
  border: 1px solid #e4e7ed;
  border-radius: 0.5rem;
}

.realtime-label {
  color: #909399;
  font-size: 0.9rem;
  margin-bottom: 0.5rem;
}

.realtime-value {
  font-size: 1.5rem;
  font-weight: bold;
  color: #303133;
  margin-bottom: 0.3rem;
}

.realtime-change.positive {
  color: #67c23a;
}

.realtime-change.negative {
  color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-section {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .header-right {
    flex-direction: column;
    width: 100%;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
    padding: 1rem;
  }
  
  .charts-section,
  .data-table-section,
  .realtime-section {
    padding: 0 1rem 2rem;
  }
  
  .table-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
  
  .table-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .realtime-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .realtime-grid {
    grid-template-columns: 1fr;
  }
  
  .table-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .table-actions .el-input,
  .table-actions .el-select {
    width: 100% !important;
  }
}
</style>